/**
 * 
 */
package info.niwota.start;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;

/**
 * @author qiangli
 * 
 */
public class ImageUtil {
	public static Drawable filter(Drawable icon) {
		if (icon == null) {
			return null;
		}
		//Bitmap deco = null; //
		int width = 48; // 
		int height = 48; // 

		final int iconWidth = icon.getIntrinsicWidth();
		final int iconHeight = icon.getIntrinsicHeight();

		if (icon instanceof PaintDrawable) {
			PaintDrawable painter = (PaintDrawable) icon;
			painter.setIntrinsicWidth(width);
			painter.setIntrinsicHeight(height);
		}
		if (width > 0 && height > 0
				&& (width < iconWidth || height < iconHeight)) {
			final float ratio = (float) iconWidth / iconHeight;

			if (iconWidth > iconHeight) {
				height = (int) (width / ratio);
			} else if (iconHeight > iconWidth) {
				width = (int) (height * ratio);
			}

			final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
					: Bitmap.Config.RGB_565;

			final Bitmap thumb = Bitmap.createBitmap(width, height, c);
			final Canvas canvas = new Canvas(thumb);
			canvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
							0));
			// Copy the old bounds to restore them later
			// If we were to do oldBounds = icon.getBounds(),
			// the call to setBounds() that follows would
			// change the same instance and we would lose the
			// old bounds
			// mOldBounds.set(icon.getBounds());
			icon.setBounds(0, 0, width, height);
			icon.draw(canvas);
			// icon.setBounds(mOldBounds);
			//
//			if (deco != null) {
//				canvas.drawBitmap(deco, new Matrix(), null);
//			}
			//
			return new BitmapDrawable(thumb);
		}
		return icon;
	}

	/**
	 * 
	 */
	private ImageUtil() {
	}
}
